import { ref, watch, onMounted, onBeforeUnmount } from "vue";
import { useMouseTranslate } from "../common/useMouseTranslate.js";

// 初始宽度配置
const InitSideWidth = {
  InitLeftMinWidth: 600,
  InitRightMinWidth: 480,
  DragSpaceWidth: 20,
};

export function useDragWidth({
  containerRef,
  dragLineRef,
  initialRightWidth = InitSideWidth.InitRightMinWidth,
  leftMinWidth = InitSideWidth.InitLeftMinWidth,
  rightMinWidth = InitSideWidth.InitRightMinWidth,
}) {
  const { x, isMoving } = useMouseTranslate(dragLineRef);

  const rightWidth = ref(initialRightWidth);
  const initLeftMinWidth = leftMinWidth;
  const initRightMinWidth = rightMinWidth;

  const updateWidths = () => {
    const containerWidth = containerRef.value?.clientWidth || 0;
    /**
     * 1、窗口过小时固定的左右最小宽度大于浏览器视口，重新按比例计算左右最小宽度
     * 2、防止左右比例占满总比例，预留一些宽度用于拖动(DragSpaceWidth)
     * 3、(可修改为只计算一侧的最大宽度和最小宽度)
     */
    if (initLeftMinWidth + initRightMinWidth >= containerWidth) {
      const totalProportion =
        InitSideWidth.InitRightMinWidth +
        InitSideWidth.InitLeftMinWidth +
        InitSideWidth.DragSpaceWidth;
      leftMinWidth =
        (InitSideWidth.InitLeftMinWidth / totalProportion) * containerWidth;
      rightMinWidth =
        (InitSideWidth.InitRightMinWidth / totalProportion) * containerWidth;
      initialRightWidth = rightMinWidth;
    } else {
      initialRightWidth = rightMinWidth = InitSideWidth.InitRightMinWidth;
      leftMinWidth = InitSideWidth.InitLeftMinWidth;
    }
  };

  onMounted(() => {
    window.addEventListener("resize", updateWidths);
    updateWidths();
  });

  onBeforeUnmount(() => {
    window.removeEventListener("resize", updateWidths);
  });

  // 监听鼠标位置，修改右侧区域宽度，实现拖拽效果
  watch(
    () => x.value,
    (newX) => {
      if (!isMoving.value) return;

      const containerWidth = containerRef.value?.clientWidth || 0;
      const dragLineWidth = dragLineRef.value?.offsetWidth || 0;
      const maxWidth = containerWidth - (leftMinWidth + dragLineWidth);

      if (containerWidth) {
        let newWidth = containerWidth - newX;
        if (newWidth < rightMinWidth) {
          newWidth = rightMinWidth;
        } else if (newWidth > maxWidth) {
          newWidth = maxWidth;
        }
        rightWidth.value = newWidth;
      }
    },
    { immediate: true }
  );

  return {
    isMoving,
    rightWidth,
  };
}
